package com.sjf.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test/sql")
public class TestSqlController {

    private static final String JDBC_DRIVER = "org.elasticsearch.xpack.sql.jdbc.EsDriver";
    private String elasticsearchAddress = "192.168.228.100:9200";

    @GetMapping("sql/jdbc/text")
    public void sqlQuery ( @RequestParam(name = "sqlText") String sqlText ) {
        try {
            Class.forName (JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace ();
        }
        String address = "jdbc:es://http://" + elasticsearchAddress;
        Long total = 0L;
        List<Map<String, Object>> outputList = new ArrayList<> ();
        try (Connection connection = DriverManager.getConnection (address) ;
             Statement statement = connection.createStatement () ;
             ResultSet results = statement.executeQuery (sqlText)) {
            int columnCount = results.getMetaData ().getColumnCount ();
            List<String> columnNames = new ArrayList<> ();
            for ( int i = 1 ; i <= columnCount ; i++ ) {
                columnNames.add (results.getMetaData ().getColumnName (i));
            }
            while (results.next ()) {
                Map<String, Object> tempItem = new HashMap<> ();
                for ( String columnName : columnNames ) {
                    tempItem.put (columnName , results.getObject (columnName));
                }
                outputList.add (tempItem);
                total++;
            }
            System.out.println (outputList);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}